package com.hjxr.xmgl.utils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class FileNumberUtil {

    public static Map<String, Integer> map = new HashMap<>();

    public static void main(String[] args) {

        String path = "D:\\Javajdk";

        Map<String, Integer> fileMap =  fileNumber(path);

        for (String key : fileMap.keySet()) {
            System.out.println( key+ " " + fileMap.get(key));
        }
    }

    public static Map fileNumber(String path){
        File file = new File(path);
        Map <String ,Integer> fileMap;
        func(file);
        fileMap = map;
        return fileMap;
    }

    //打印所有文件(注意这时候一定加上非空判断，不然会出现NullPointerException)
    public static void func(File file) {
        int i = 0;
        String parentBefore = "";
        String parentAfter = "";
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isFile()) {
                    File parentDir = f.getParentFile();
                    File[] parentArray = parentDir.listFiles();
                    parentAfter = parentDir.getName();
                    if (!parentAfter.equals(parentBefore)) {
                        int count = parentArray.length;
                        for (File chird : parentArray) {
                            if (chird.isDirectory()) {
                                count--;
                            }
                        }
                        //System.out.println(parentDir.toString() + "-----------" + count + "个文件");
                        map.put(parentDir.toString(), count);
                    }
                    parentBefore = parentDir.getName();
//                    System.out.println(f.getParent() + " "+ i);
//                    i = 0;
                }

                if (f.isDirectory()) {
                    func(f);
                }
            }
        }
    }
}
